<template>
  <div class="login-container bgImg content">
    <div class="layout">
      <a-form-model
        :model="loginForm"
        :rules="loginRules"
        class="form-container"
        ref="loginForm"
        autocomplete="off"
        v-if="!isRegister"
      >
        <div class="title" @click="handleToIndex">
          <img style="width: 46px; height: 46px" src="@/assets/home/logo.png" />
          <img style="width: 374px; height: 36px" src="@/assets/home/logo2.png" />
        </div>
        <div class="top-box">
          <div class="item" :class="[currentTab == 'user' ? 'itemActive' : '']" @click="handleCurrent('user')">
            账号登录
          </div>
          <div class="item" :class="[currentTab == 'phone' ? 'itemActive' : '']" @click="handleCurrent('phone')">
            验证码登录
          </div>
        </div>
        <div v-if="currentTab === 'user'" class="formTitle">手机号</div>
        <a-form-model-item style="width: 100%" prop="userAccount" v-if="currentTab === 'user'">
          <a-input
            v-model="loginForm.userAccount"
            placeholder="请输入账号 (admin or test or editor)"
            size="large"
            allow-clear
            @pressEnter="focusPassword"
            autocomplete="off"
          >
            <a-icon slot="prefix" type="user" />
          </a-input>
        </a-form-model-item>
        <div v-if="currentTab === 'user'" class="formTitle">密码</div>
        <a-form-model-item style="width: 100%" prop="password" v-if="currentTab === 'user'">
          <a-input-password
            v-model="loginForm.password"
            placeholder="请输入密码 (任意输入6位数)"
            size="large"
            allow-clear
            @pressEnter="toLogin"
            autocomplete="new-password"
            ref="password"
          >
            <svg-icon icon="password" :size="14" slot="prefix"> </svg-icon>
          </a-input-password>
        </a-form-model-item>
        <a-form-model-item style="width: 100%" prop="phone" v-if="currentTab === 'phone'">
          <a-input
            v-model="loginForm.phone"
            placeholder="请输入手机号"
            size="large"
            allow-clear
            :maxLength="11"
            autocomplete="off"
            type="text"
          >
            <svg-icon icon="phone" :size="14" slot="prefix"> </svg-icon>
          </a-input>
        </a-form-model-item>

        <a-form-model-item style="width: 100%" prop="code" v-if="currentTab === 'phone'">
          <a-input
            v-model="loginForm.code"
            placeholder="请输入验证码"
            size="large"
            :maxLength="6"
            style="width: 58%"
            ref="code"
            @pressEnter="toLogin"
          >
          </a-input>
          <a-button
            size="large"
            class="my-btn"
            @click="getCode"
            :disabled="codeStatus"
            style="width: 40%; margin-left: 2%"
            >{{ phoneCode }}</a-button
          >
        </a-form-model-item>
        <a-form-item style="margin-top: -7px; width: 100%">
          <div style="display: flex; justify-content: space-between">
            <span class="forge-password pointer" @click="handleRegister">注册</span>
            <span class="forge-password pointer" @click="handleForgePsw">忘记密码？</span>
          </div>
        </a-form-item>
        <a-form-item style="margin-top: -7px; width: 100%">
          <a-button class="my-btn-login" block size="large" :loading="loading" @click="toLogin"> 登录 </a-button>
        </a-form-item>

        <!-- <a-form-item style="margin-top: -20px">
          <span style="margin-right: 15px">其他登录方式</span>
          <svg-icon icon="weixin" :size="25" class="pointer verticalMiddle"></svg-icon>
          <svg-icon icon="qq" :size="25" style="margin: 0 14px" class="pointer verticalMiddle"></svg-icon>
          <svg-icon icon="zhifubao" :size="25" class="pointer verticalMiddle"></svg-icon>
          <span class="forge-password pointer">注册账户</span>
        </a-form-item> -->
      </a-form-model>
      <a-form-model
        :model="loginForm"
        :rules="loginRules"
        class="form-container form-container-pad"
        ref="loginForm"
        autocomplete="off"
        v-else
      >
        <div class="backLogin" @click="handleBackLogin">已有账户， 返回登录</div>
        <div class="register">用户注册</div>
        <div class="formTitle">手机号</div>
        <a-form-model-item style="width: 100%" prop="phone">
          <a-input v-model="loginForm.phone" placeholder="请输入手机号" size="large" allow-clear> </a-input>
        </a-form-model-item>
        <div class="formTitle">验证码</div>
        <a-form-model-item style="width: 100%" prop="code">
          <a-input
            v-model="loginForm.code"
            placeholder="请输入验证码"
            size="large"
            :maxLength="6"
            style="width: 58%"
            ref="code"
          >
          </a-input>
          <a-button
            size="large"
            class="my-btn"
            @click="getCode"
            :disabled="codeStatus"
            style="width: 40%; margin-left: 2%"
            >{{ phoneCode }}</a-button
          >
        </a-form-model-item>
        <div class="formTitle">姓名</div>
        <a-form-model-item style="width: 100%" prop="userName">
          <a-input v-model="loginForm.userName" placeholder="请输入您的姓名" size="large" allow-clear> </a-input>
        </a-form-model-item>
        <div class="formTitle">密码</div>
        <a-form-model-item style="width: 100%" prop="password">
          <a-input-password
            v-model="loginForm.password"
            placeholder="请输入密码"
            size="large"
            allow-clear
            ref="password"
          >
            <svg-icon icon="password" :size="14" slot="prefix"> </svg-icon>
          </a-input-password>
        </a-form-model-item>
        <div class="formTitle">重复密码</div>
        <a-form-model-item style="width: 100%" prop="password2">
          <a-input-password
            v-model="loginForm.password2"
            placeholder="请再次输入密码"
            size="large"
            allow-clear
            ref="password2"
          >
            <svg-icon icon="password" :size="14" slot="prefix"> </svg-icon>
          </a-input-password>
        </a-form-model-item>
        <a-form-item style="width: 100%; margin-top: -7px">
          <a-checkbox v-model="loginForm.checked">
            <span class="text1">已阅读并同意</span>
          </a-checkbox>
          <span class="text2" @click="handleAgreement">用户协议</span>
          <span class="text1">和</span>
          <span class="text2" @click="handlePrivacy">隐私政策</span>
        </a-form-item>
        <a-form-item style="margin-top: -7px; width: 100%">
          <a-button class="my-btn-login" block size="large" :loading="loading" @click="toRegister"> 注册 </a-button>
        </a-form-item>
      </a-form-model>
    </div>
    <MyModal :visible="forgePaswordVisible" :width="500" :title="'忘记密码'" @handleCancel="handleCancel">
      <template #dialogBox>
        <ForgePassword @cancel="handleCancel" />
      </template>
    </MyModal>
  </div>
</template>

<script>
import { isPhone, isPassWord, isCode } from '@/utils/validate';
import { getCache, setCache, removeCache } from '@/utils/session';
import { getPhoneCode, registerUser } from '@/api/user';
import { Md5 } from 'ts-md5/dist/md5';
import MyModal from '@/components/MyModal';

import ForgePassword from './ForgePassword.vue';

export default {
  name: 'login',
  components: { ForgePassword, MyModal },
  data() {
    const validateUsername = (rule, value, callback) => {
      if (value.trim().length === 0) {
        callback(new Error('用户名不能为空'));
      } else {
        callback();
      }
    };
    const validateUserName2 = (rule, value, callback) => {
      if (value.trim().length === 0) {
        callback(new Error('姓名不能为空'));
      } else {
        callback();
      }
    };
    const validatePassword = (rule, value, callback) => {
      // if (!isPassWord(value)) {
      //   callback(new Error('请正确输入密码'));
      // } else {
      //   callback();
      // }
      if (value.trim().length === 0) {
        callback(new Error('密码不能为空'));
      } else {
        callback();
      }
    };
    const validatePassword2 = (rule, value, callback) => {
      // if (!isPassWord(value)) {
      //   callback(new Error('请正确输入密码'));
      // } else {
      //   callback();
      // }
      if (value.trim().length === 0) {
        callback(new Error('密码不能为空'));
      } else {
        callback();
      }
    };
    const validatePhone = (rule, value, callback) => {
      if (!value) {
        callback(new Error('手机号不能为空'));
      } else if (!isPhone(value)) {
        callback(new Error('手机号码有误，请重新填写'));
      } else {
        callback();
      }
    };
    const validateCode = (rule, value, callback) => {
      if (!isCode(value)) {
        callback(new Error('验证码有误，请重新填写'));
      } else {
        callback();
      }
    };

    return {
      currentTab: 'user',
      loginForm: {
        userAccount: '',
        password: '',
        phone: '',
        code: '',
        remember: true,
        userName: '',
        password2: '',
        checked: false
      },
      loginRules: {
        userAccount: [{ required: true, trigger: 'blur', validator: validateUsername }],
        password: [{ required: true, trigger: 'blur', validator: validatePassword }],
        password2: [{ required: true, trigger: 'blur', validator: validatePassword2 }],
        phone: [{ required: true, trigger: 'blur', validator: validatePhone }],
        code: [{ required: true, trigger: 'blur', validator: validateCode }],
        userName: [{ required: true, trigger: 'blur', validator: validateUserName2 }]
      },
      loading: false,
      phoneCode: '获取验证码',
      codeStatus: false,
      forgePaswordVisible: false,
      isRegister: false
    };
  },
  mounted() {
    // const cache = getCache('LOGIN_INFO');
    // if (cache) {
    //   this.loginForm.userAccount = cache.userAccount;
    //   this.loginForm.password = cache.password;
    // }
  },
  methods: {
    focusPassword() {
      this.$refs.password.focus();
    },
    //获取验证码
    getCode() {
      if (isPhone(this.loginForm.phone)) {
        this.codeStatus = true;
        getPhoneCode(this.loginForm.phone)
          .then(res => {
            let time = 60;
            var getPhoneIntval = setInterval(() => {
              if (time > 0) {
                time--;
                this.phoneCode = `重新获取(${time}s)`;
              } else {
                clearInterval(getPhoneIntval);
                getPhoneIntval = null;
                this.phoneCode = '获取验证码';
                this.codeStatus = false;
              }
            }, 1000);
            this.$refs.code.focus();
          })
          .catch(() => {
            this.codeStatus = false;
          });
      } else {
        this.$message.error('请正确输入手机号');
      }
    },
    //登录
    toLogin() {
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          this.loading = true;
          if (this.currentTab === 'user') {
            const { userAccount, password } = this.loginForm;
            this.$store
              .dispatch('user/login', { userAccount, password: Md5.hashStr(password) })
              .then(() => {
                if (this.loginForm.remember) {
                  setCache('LOGIN_INFO', { userAccount, password });

                  this.$router.push({
                    path: '/index'
                  });
                  this.loading = false;
                } else {
                  removeCache('LOGIN_INFO');
                }
              })
              .catch(() => {
                setTimeout(() => {
                  this.loading = false;
                }, 500);
              });
          } else if (this.currentTab === 'phone') {
            const { phone, code } = this.loginForm;
            this.$store
              .dispatch('user/codeTest', { userAccount: phone, code })
              .then(() => {
                removeCache('LOGIN_INFO');
                this.$router.push({
                  path: '/index'
                });
                this.loading = false;
              })
              .catch(() => {
                setTimeout(() => {
                  this.loading = false;
                }, 500);
              });
          }
        } else {
          return false;
        }
      });
    },
    // 注册
    toRegister() {
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          const { phone, code, userName, password, password2, checked } = this.loginForm;
          if (!checked) {
            this.$message.error('请阅读并勾选以下协议');
            return;
          }
          this.loading = true;
          registerUser({
            userName,
            userAccount: phone,
            userPwd: Md5.hashStr(password),
            confirmPassword: Md5.hashStr(password2),
            code
          })
            .then(res => {
              this.loading = false;

              if (res.code == 0) {
                this.$message.success('注册成功，即将返回登录页');
                setTimeout(() => {
                  this.isRegister = false;
                  this.loginForm = {
                    userAccount: '',
                    password: '',
                    phone: '',
                    code: '',
                    remember: true,
                    userName: '',
                    password2: '',
                    checked: false
                  };
                }, 1000);
              } else {
                this.$message.error(res.message);
              }
            })
            .catch(() => {
              setTimeout(() => {
                this.loading = false;
              }, 500);
            });
        } else {
          return false;
        }
      });
    },
    handleCurrent(type) {
      this.currentTab = type;
    },
    handleForgePsw() {
      this.forgePaswordVisible = true;
    },
    handleCancel() {
      this.forgePaswordVisible = false;
    },
    handleToIndex() {
      this.$router.push({
        path: './index'
      });
    },
    handleRegister() {
      this.isRegister = true;
      this.loginForm = {
        userAccount: '',
        password: '',
        phone: '',
        code: '',
        remember: true,
        userName: '',
        password2: '',
        checked: false
      };
    },
    handleBackLogin() {
      this.isRegister = false;
      this.loginForm = {
        userAccount: '',
        password: '',
        phone: '',
        code: '',
        remember: true,
        userName: '',
        password2: '',
        checked: false
      };
    },
    handleAgreement() {
      window.open('http://hydrobim.douziit.com/agreement.html', '_blank');
    },
    handlePrivacy() {
      window.open('http://hydrobim.douziit.com/privacy.html', '_blank');
    }
  }
};
</script>
<style lang="scss" scoped>
.ant-form-item ::v-deep .ant-input {
  background: rgba(22, 102, 240, 0.2);
  border: 1px solid #1666f0;
  color: #fff;
}
.ant-form-item ::v-deep i {
  color: #fff;
}
.ant-form-item ::v-deep .ant-input-prefix {
  color: #fff;
}
.login-container {
  background: url('https://dztest2.obs.cn-southwest-2.myhuaweicloud.com/hydrobim/banner/main-bg.jpg');
  background-size: cover;
  height: 100%;
  .layout {
    width: 55%;
    min-width: 900px;
    position: absolute;
    top: 50%;
    left: 50%;
    translate: -50% -50%;
    .form-container {
      width: 55%;
      margin: 0 auto;
      background: #021c2e;
      box-shadow: 0px 0px 6px #1666f0;
      padding: 80px 90px;
      color: #fff;
      display: flex;
      flex-direction: column;
      align-items: center;
      max-height: 80vh;
      overflow-y: auto;
      overflow-x: hidden;
      .registerBox {
        margin-bottom: -20px;
      }
      .backLogin {
        position: absolute;
        top: 24px;
        right: 24px;
        font-size: 14px;
        font-weight: 400;
        color: rgba(255, 255, 255, 0.5);
      }
      .register {
        width: 100%;
        font-size: 30px;
        margin-bottom: 40px;
      }
      .formTitle {
        width: 100%;
        font-size: 16px;
        margin-bottom: 4px;
        color: #ffffff;
      }
      .top-box {
        width: 300px;
        height: 48px;
        background: rgba(22, 102, 240, 0.2);
        font-size: 18px;
        padding: 4px;
        display: flex;
        margin-bottom: 60px;
        margin-top: 40px;
        .item {
          width: 50%;
          height: 100%;
          display: flex;
          align-items: center;
          justify-content: center;
          cursor: pointer;
        }
        .itemActive {
          background: #1666f0;
          border-radius: 4px;
        }
      }
      .title {
        display: flex;
        align-items: center;
        font-weight: 700;
        font-size: 24px;
        height: 40px;
        img {
          width: 37px;
          height: 37px;
          margin-right: 5px;
        }
      }
      .tabs {
        margin: 15px 0;
      }
      .forge-password {
        font-size: 16px;
        color: #fff;
      }
      .my-btn {
        color: #ccc;
        background: #021c2e;
        border: 1px solid #1666f0;
      }
      .my-btn-login {
        color: #fff;
        background: #1666f0;
        border: none;
      }

      .text1 {
        color: rgba(255, 255, 255, 0.5);
        font-size: 16px;
      }
      .text2 {
        color: #ffffff;
        border-bottom: 1px solid #ffffff;
        font-size: 16px;
        margin: 0 4px;
      }
    }
    .form-container-pad {
      padding: 60px 90px;
      position: relative;
    }
    .form-container::-webkit-scrollbar {
      display: none; /*隐藏滚动条*/
    }
  }
}
</style>
<style lang="scss">
.login-container {
  .ant-tabs-bar {
    border-bottom: none !important;
  }
  .ant-input-affix-wrapper .ant-input:not(:first-child) {
    padding-left: 35px !important;
  }
  .ant-tabs-bar {
    margin-bottom: 30px !important;
  }
}
.has-error .ant-input-affix-wrapper .ant-input,
.has-error .ant-input-affix-wrapper .ant-input:hover {
  background-color: rgba(22, 102, 240, 0.2);
}

.ant-checkbox-inner {
  background-color: rgba(22, 102, 240, 0.2);
  border-color: #1666f0;
}
.ant-checkbox-checked .ant-checkbox-inner {
  background-color: rgba(22, 102, 240, 0.2);
}
</style>
